home *** CD-ROM | disk | FTP | other *** search
- Path: abacus.abasoft.co.uk!not-for-mail
- From: dmb@abacus.abasoft.co.uk (David Byrne)
- Newsgroups: comp.lang.c++
- Subject: Re: Major problem with strings.
- Date: 14 Mar 1996 10:52:43 -0000
- Organization: Abacus Software Ltd.
- Message-ID: <4i8tpr$1he@abacus.abasoft.co.uk>
- References: <31438275.72DB@aol2.com> <4i0gn0$5g9@sam.inforamp.net>
- NNTP-Posting-Host: abacus.abasoft.co.uk
- X-NNTP-Posting-Host: abacus.demon.co.uk
-
- In article <4i0gn0$5g9@sam.inforamp.net>,
- Randy Charles Morin <rmorin@inforamp.net> wrote:
- >In article <31438275.72DB@aol2.com>, Neil <neil@aol2.com> wrote:
- [code snipped]
- >No, this just won't do. When you want a '/' slash in C, use two slashes. The
- >'/' is also used to denote an escape sequence (for special characters). Thus
- >your code should read...
- >
- >1 char *club="";
- >2 club="//public_html//neil";
- >3 strcat(club,argv[1]+5);
- >4 strcat(club,"//");
-
- This is a joke, right ?
-
- Neil: line 1: club is declared as a char*
- line 2: an area of memory is initialised with the string
- "/public_html/neil" (The '/' characters are correct, '\' is the escape
- char which you need to double up to get a genuine backslash)
- line 3: all characters from the sixth character of the first argument up
- to the next null character are copied over whatever data is in memory
- after the area of memory allocated in line 2 (A *BAD* thing !)
- line 4: more data trashing
-
- Try something like:
-
- ...
-
- // work out a suitable size depending on what your longest argument is
- const int MAX_ARG_LEN=20;
- const char* base_dir="/public_html/neil";
-
- int main(int argc, char **argv)
- {
- char *club=new char[strlen(base_dir) + MAX_ARG_LEN + 1];
-
- if (argc > 1)
- {
- // put some sort of check here to ensure we only copy MAX_ARG_LEN chars
- // or use strncat with appropriate args etc.
- strcat(club, argv[1]+5);
- strcat(club,"/");
- }
-
- // etc. etc.
-
- delete[] club;
- }
-
-
- I think a nicer way to do this is:
-
- #include <iostream.h>
- #include <strstream.h>
- #include <string.h>
-
- const char* base_dir="/public_html/neil";
-
- int main(int argc, char **argv)
- {
- ostrstream os;
-
- os << base_dir;
- if (argc > 1)
- os << argv[1]+5 << "/";
-
- char *club=os.str();
-
- // use club for whatever purposes
- cout << club << endl;
-
- delete[] club;
- // etc. etc.
- }
-
- You could also consider using a string class or STL vector<char> to store the
- data in as alternatives.
-
- David
- --
- David Byrne, Abacus Software, London, UK Tel: +44 (0)171 603 9877
- Email: dmb@abacus.demon.co.uk Fax: +44 (0)171 603 6844
- Here's a koan: If you have ice-cream I will give you some. If you have none,
- I will take it away from you. (it's an ice-cream koan).
-